package com.dede.localdex;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author hsh
 * @time 2017/7/25 025 上午 10:11.
 * @doc
 */
public class JavaShellUtil {

    public static String lineSeparator;
    public static String COMMAND_SH;
    public static String COMMAND_EXIT = "exit\n";
    public static String COMMAND_LINE_END = "\n";

    private static String OS_NAME;

    static {
        lineSeparator = System.getProperty("line.separator");
        OS_NAME = System.getProperty("os.name");
        System.out.println(OS_NAME);
        if (OS_NAME.toUpperCase().contains("WINDOWS")) {
            COMMAND_SH = "cmd";
        } else {
            COMMAND_SH = "sh";
        }

    }

    public static void root(boolean isRoot) {
        COMMAND_SH = isRoot ? "su" : "sh";
    }

    public static CommandResult execCommand(String command) {
        return execCommand(new String[]{command}, false);
    }

    public static CommandResult execCommand(String command, boolean isNeedResultMsg) {
        return execCommand(new String[]{command}, isNeedResultMsg);
    }

    public static CommandResult execCommand(List<String> commands, boolean isNeedResultMsg) {
        return execCommand(commands == null ? null : commands.toArray(new String[]{}), isNeedResultMsg);
    }

    public static CommandResult execCommand(boolean isNeedResultMsg, String... args) {
        return execCommand(args, isNeedResultMsg);
    }

    /**
     * execute shell commands
     * {@link CommandResult#result} is -1, there maybe some excepiton.
     *
     * @param commands     command array
     * @param needResponse whether need result msg
     */
    public static CommandResult execCommand(String[] commands, final boolean needResponse) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, "空命令");
        }

        Process process = null;

        final StringBuilder successMsg = new StringBuilder();
        final StringBuilder errorMsg = new StringBuilder();

        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec(COMMAND_SH);
            os = new DataOutputStream(process.getOutputStream());
            for (String command : commands) {
                if (command == null) {
                    continue;
                }
                // donnot use os.writeBytes(commmand), avoid chinese charset error
                os.write(command.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();

            final BufferedReader successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            final BufferedReader errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));

            if (needResponse) {
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            String s;
                            while ((s = successResult.readLine()) != null) {
                                successMsg.append(s);
                                successMsg.append(lineSeparator);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
                //启动两个线程,解决process.waitFor()阻塞问题
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            String s;
                            while ((s = errorResult.readLine()) != null) {
                                errorMsg.append(s);
                                errorMsg.append(lineSeparator);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
            result = process.waitFor();
            if (errorResult != null) {
                errorResult.close();
            }
            if (successResult != null) {
                successResult.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignored) {
                }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return new CommandResult(result, successMsg == null ? null :
                (successMsg.length() == 0 ? "" : successMsg.deleteCharAt(successMsg.length() - 1).toString()),
                errorMsg == null ? null : (errorMsg.length() == 0 ? "" : errorMsg.deleteCharAt(errorMsg.length() - 1).toString()));
    }

    public static class CommandResult {

        private int result;
        private String responseMsg;
        private String errorMsg;

        public int getResult() {
            return result;
        }

        public void setResult(int result) {
            this.result = result;
        }

        public String getResponseMsg() {
            return responseMsg;
        }

        public void setResponseMsg(String responseMsg) {
            this.responseMsg = responseMsg;
        }

        public String getErrorMsg() {
            return errorMsg;
        }

        public void setErrorMsg(String errorMsg) {
            this.errorMsg = errorMsg;
        }

        private CommandResult(int result, String responseMsg, String errorMsg) {
            this.result = result;
            this.responseMsg = responseMsg;
            this.errorMsg = errorMsg;
        }

        @Override
        public String toString() {
            return "CommandResult{" +
                    "errorMsg='" + errorMsg + '\'' +
                    ", result=" + result +
                    ", responseMsg='" + responseMsg + '\'' +
                    '}';
        }
    }
}
